package itbour.onetouchshow.activity.challengezone.video;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLCameraSetting;
import com.qiniu.pili.droid.shortvideo.PLMicrophoneSetting;
import com.qiniu.pili.droid.shortvideo.PLRecordSetting;
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder;
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;

import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.widget.SquareGLSurfaceView;
import itbour.onetouchshow.widget.VideoRecordProgress;

/**
 * Created by guoh on 2018/7/11.
 * 功能描述：1:1视频拍摄的优化处理 使用FFmpeg
 * 需要的参数：
 */
public class VideoRecordQiNiuActivity extends MVPBaseActivity {

    private ImageView mImgStartRecord;
    private TextView mTvReRecord;
    private TextView mTvChoose;
    private ImageView mImgBack;
    private VideoRecordProgress recordProgress;
    private SquareGLSurfaceView mSurfaceView;

    //是否正在录像
    private boolean isRecording = false;
    //当前录制的时间 秒
    private int recordSeconds = -1;
    //最小录制时间 秒
    private int minRecordSeconds = 3;
    //最大录制时间
    private int maxRecordSeconds = 60;
    //文件输出路径
    private String cachePath = AppCache.getInstance().VIDEO_SAVE_DIR;
    //视频保存路径
    private String outputPath;

    private PLShortVideoRecorder mShortVideoRecorder;

    //配置的参数
    private PLCameraSetting mCameraSetting;
    private PLMicrophoneSetting mMicrophoneSetting;
    private PLRecordSetting mRecordSetting;
    private PLVideoEncodeSetting mVideoEncodeSetting;
    private PLAudioEncodeSetting mAudioEncodeSetting;

    //视频录制的速度
    private double mRecordSpeed = 1;

    //计时
    private Handler timeHandler;

    private Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            recordSeconds += 1;
            if (recordSeconds == maxRecordSeconds) {
                //到达最大录制时间
                stopRecord();
                isRecording = false;
            } else {
                timeHandler.postDelayed(this, 1000);
            }
            if (recordProgress.getVisibility() == View.VISIBLE) {
                recordProgress.setProgress(recordSeconds);
            }


        }
    };

    public static Intent getLaunchIntent(Context context, int maxRecordSeconds) {
        Intent intent = new Intent(context, VideoRecordQiNiuActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_RECORD_MAX_SECONDS, maxRecordSeconds);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        return R.layout.ac_video_record_qiniu;
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        initViews();
        initDatas();
        addListeners();
    }

    private void initViews() {
        mSurfaceView = findViewById(R.id.surfaceview);
        mImgStartRecord = findViewById(R.id.iv_start_image);
        mTvChoose = findViewById(R.id.tv_choose);
        mTvReRecord = findViewById(R.id.tv_re_record);
        mImgBack = findViewById(R.id.iv_back);
        recordProgress = findViewById(R.id.record_progress);
    }

    private void initDatas() {
        maxRecordSeconds = getIntent().getIntExtra(AppConst.KEY_VIDEO_RECORD_MAX_SECONDS, 60);
        timeHandler = new Handler();
        outputPath = cachePath + "/" + "one_to_one.mp4";

        mShortVideoRecorder = new PLShortVideoRecorder();
        mCameraSetting = new PLCameraSetting();
        PLCameraSetting.CAMERA_FACING_ID facingId = chooseCameraFacingId();
        mCameraSetting.setCameraId(facingId);
        //预览比例
        mCameraSetting.setCameraPreviewSizeRatio(PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO.RATIO_4_3);
        //预览分辨率
        mCameraSetting.setCameraPreviewSizeLevel(PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_720P);
        mMicrophoneSetting = new PLMicrophoneSetting();
        mMicrophoneSetting.setChannelConfig(AudioFormat.CHANNEL_IN_MONO);
        mVideoEncodeSetting = new PLVideoEncodeSetting(this);
        //视频输出大小
        mVideoEncodeSetting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_720P_1);
        //比特率
        mVideoEncodeSetting.setEncodingBitrate(4000 * 1000);
        //编码类型HW
        mVideoEncodeSetting.setHWCodecEnabled(true);
        mAudioEncodeSetting = new PLAudioEncodeSetting();
        //编码类型HW
        mAudioEncodeSetting.setHWCodecEnabled(true);
        //单身道
        mAudioEncodeSetting.setChannels(1);
        mRecordSetting = new PLRecordSetting();
        //最大录制时长
        mRecordSetting.setMaxRecordDuration((long) (maxRecordSeconds * 1000 * mRecordSpeed));
        mRecordSetting.setVideoCacheDir(cachePath);
        mRecordSetting.setVideoFilepath(outputPath);

        mShortVideoRecorder.prepare(mSurfaceView, mCameraSetting, mMicrophoneSetting, mVideoEncodeSetting,
                mAudioEncodeSetting, null, mRecordSetting);

        mShortVideoRecorder.setRecordSpeed(mRecordSpeed);
        recordProgress.setTotalCount(maxRecordSeconds);
    }

    private void addListeners() {
        mImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTvChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recordSeconds < minRecordSeconds) {
                    T_.showCustomToast("录制视频时长过短");
                    return;
                }
                mShortVideoRecorder.concatSections(new PLVideoSaveListener() {
                    @Override
                    public void onSaveVideoSuccess(final String s) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent();
                                intent.putExtra(AppConst.KEY_RECORD_VIDEO_PATH, outputPath);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        });

                    }

                    @Override
                    public void onSaveVideoFailed(int i) {
                    }

                    @Override
                    public void onSaveVideoCanceled() {

                    }

                    @Override
                    public void onProgressUpdate(float v) {

                    }
                });
            }
        });
        mImgStartRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isRecording) {
                    startRecord();
                } else {
                    if (isRecording) {
                        if (recordSeconds < minRecordSeconds) {
                            T_.showCustomToast("录制视频时长过短");
                            return;
                        }
                        stopRecord();
                        isRecording = false;
                    }
                }
            }
        });
        mTvReRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mShortVideoRecorder.deleteAllSections();
                resetProgress();
                mTvChoose.setVisibility(View.GONE);
                mTvReRecord.setVisibility(View.GONE);
                mImgStartRecord.setBackground(VideoRecordQiNiuActivity.this.getResources().getDrawable(R.mipmap.icon_video_record_start));
                mImgStartRecord.setEnabled(true);
            }
        });
    }

    //开始录制视频
    private void startRecord() {
        if (mShortVideoRecorder.beginSection()) {
            isRecording = true;
            recordProgress.setVisibility(View.VISIBLE);
            mTvChoose.setVisibility(View.GONE);
            mTvReRecord.setVisibility(View.GONE);
            timeHandler.post(timeRunnable);
        } else {
            T_.showCustomToast("无法开始视频段录制");
        }
    }

    //停止录制视频
    private void stopRecord() {
        timeHandler.removeCallbacks(timeRunnable);
        mShortVideoRecorder.endSection();
        mImgStartRecord.setBackground(VideoRecordQiNiuActivity.this.getResources().getDrawable(R.mipmap.icon_video_record_enable));
        mTvChoose.setVisibility(View.VISIBLE);
        mTvReRecord.setVisibility(View.VISIBLE);
        mImgStartRecord.setEnabled(false);
    }

    //重置进度
    private void resetProgress() {
        if (recordProgress.getVisibility() == View.VISIBLE) {
            recordProgress.resetProgress();
            recordProgress.setVisibility(View.GONE);
        }
        recordSeconds = 0;
    }

    @Override
    public void loadSucceed(String result) {
    }

    @Override
    public void loadFaild(String error) {
    }

    private PLCameraSetting.CAMERA_FACING_ID chooseCameraFacingId() {
        if (PLCameraSetting.hasCameraFacing(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_3RD)) {
            return PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_3RD;
        } else if (PLCameraSetting.hasCameraFacing(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_BACK)) {
            return PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_BACK;
        } else {
            return PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_FRONT;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mShortVideoRecorder.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mShortVideoRecorder.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mShortVideoRecorder.destroy();
        timeHandler.removeCallbacks(timeRunnable);
    }
}
